﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;
using Newtonsoft.Json.Linq;
using System.Net.Sockets;
using WTAppletProjectHTTPS.App_Start;

namespace WTAppletProjectHTTPS.Controllers
{


    public class AppletUserController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // POST api/<controller>
        public class AddUser
        {
            public string Name { get; set; }
            public string Phone { get; set; }
            public string MM { get; set; }

            public string Code { get; set; }
        }

        public class FHClass
        {
            public string Name { get; set; }
            public string Phone { get; set; }
            public string Token { get; set; }
        }
        FHClass FHC = new FHClass();
        public async Task<HttpResponseMessage> Post([FromBody] AddUser AR)
        {
            ReturnObject RO = new ReturnObject();
            if (AR.MM != "HSY" + DateTime.Now.ToString("yyyyMMdd"))
            {
                Logger.Error("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }
            
            AppletUser AU = new AppletUser();
            // 读取响应内容为字符串
            string responseBody = "";
            using (HttpClient client = new HttpClient())
            {
                string AppId = ConfigurationManager.AppSettings["AppId"];
                string Secret = ConfigurationManager.AppSettings["Secret"];
                // 设置请求的 URL
                string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={AppId}&secret={Secret}&js_code={AR.Code}&grant_type=authorization_code";
                try
                {
                    // 发送 GET 请求并获取响应
                    HttpResponseMessage response = await client.GetAsync(url);

                    // 确保响应状态码为成功状态
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容为字符串
                    responseBody = await response.Content.ReadAsStringAsync();
                    JObject json = JObject.Parse(responseBody);
                    string OpenID = json["openid"].ToString();
                    AU.AUOpenID = OpenID;

                }
                catch (HttpRequestException ex)
                {
                    Logger.Error("Error:" + ex.Message);
                    RO.Status = HttpStatusCode.InternalServerError;
                    RO.Message = "Error:" + ex.Message;
                    RO.Data = null;
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                }
            }
            AU.AUUsername = AR.Name;
            AU.AUPhoneNumber = AR.Phone;
            
            if (AU == null ||
                string.IsNullOrEmpty(AU.AUUsername) ||
                string.IsNullOrEmpty(AU.AUPhoneNumber) ||
                string.IsNullOrEmpty(AU.AUOpenID))
            {
                Logger.Warn("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }
            Task<bool> JG = QueryUser(AU.AUOpenID);
            if (await JG)
            {
                Logger.Warn("您的账号已经创建过了，请不要重复创建");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "您的账号已经创建过了，请不要重复创建";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }
            else
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    connection.Open();
                    using (var transaction = connection.BeginTransaction())
                    {
                        try
                        {
                            var query = @"INSERT INTO AppletUser 
                                    (AUUsername, AUUserAccount, AUUserPassword, AUPhoneNumber, AUWeChatID,AUOpenID, AUEmail, AUCreationDate)
                                    VALUES 
                                    (@Username, @UserAccount, @UserPassword, @PhoneNumber, @WeChatID,@OpenID, @Email, @CreationDate);
                                    SELECT CAST(scope_identity() AS int);";

                            SqlParameter[] parameters = {
                            new SqlParameter("@Username", SqlDbType.NVarChar, 50) { Value = AU.AUUsername },
                            new SqlParameter("@UserAccount", SqlDbType.NVarChar, 50) { Value = "" },
                            new SqlParameter("@UserPassword", SqlDbType.NVarChar, 50) { Value = "" },
                            new SqlParameter("@PhoneNumber", SqlDbType.NVarChar, 50) { Value = AU.AUPhoneNumber },
                            new SqlParameter("@WeChatID", SqlDbType.NVarChar, 50) { Value = "" },
                            new SqlParameter("@OpenID", SqlDbType.NVarChar, 50) { Value = AU.AUOpenID },
                            new SqlParameter("@Email", SqlDbType.NVarChar, 50) { Value = "" },
                            new SqlParameter("@CreationDate", SqlDbType.DateTime) { Value = DateTime.Now }
                        };

                            using (var command = new SqlCommand(query, connection, transaction))
                            {
                                command.Parameters.AddRange(parameters);
                                var result = await command.ExecuteScalarAsync();
                                if (result != null)
                                {
                                    transaction.Commit();
                                    string ToK = TokenManager.GenerateToken(ConfigurationManager.AppSettings["JwtSecret"]);
                                    WebApiApplication.TK = ToK;

                                    FHC.Name = AU.AUUsername;
                                    FHC.Phone = AU.AUPhoneNumber;
                                    FHC.Token = ToK;

                                    AU.AUID = Convert.ToInt32(result);

                                    RO.Status = HttpStatusCode.OK;
                                    RO.Message = "OK";
                                    RO.Data = FHC;
                                    return Request.CreateResponse(HttpStatusCode.OK, RO);
                                }
                                else
                                {
                                    transaction.Rollback();
                                    RO.Status = HttpStatusCode.InternalServerError;
                                    RO.Message = "Error";
                                    RO.Data = null;
                                    return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Logger.Warn("新增失败: " + ex.Message);
                            RO.Status = HttpStatusCode.InternalServerError;
                            RO.Message = "Erroe: " + ex.Message;
                            RO.Data = null;
                            return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                        }
                    }
                }
            }
            
        }
        public async Task<bool> QueryUser(string OpenID)
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                try
                {
                    await connection.OpenAsync();
                    var query = @"SELECT top 1 AUID, AUUsername, AUPhoneNumber 
                                  FROM AppletUser
                                  WHERE AUOpenID = @OpenID";

                    SqlParameter[] parameters = {
                        new SqlParameter("@OpenID", SqlDbType.NVarChar, 100) { Value = OpenID }
                    };

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                return false;
                            }

                            var users = new List<AppletUser>();
                            while (await reader.ReadAsync())
                            {
                                users.Add(new AppletUser
                                {
                                    AUID = reader.GetInt32(0),
                                    AUUsername = reader.GetString(1),
                                    AUPhoneNumber = reader.GetString(2)
                                });
                            }

                            if (users.Count > 0)
                            {
                                FHC.Name = users[0].AUUsername;
                                FHC.Phone = users[0].AUPhoneNumber;
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                    return false;
                }
            }
        }
    }
}